package com.example.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.example.reggie.utils.BaseContext;
import com.example.reggie.utils.R;
import com.sun.org.apache.xpath.internal.operations.Bool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class VisitFilter implements Filter {



    public final AntPathMatcher antPathMatcher=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest=(HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse=(HttpServletResponse) servletResponse;
        Object empId= httpServletRequest.getSession().getAttribute("employee");
        Object userId= httpServletRequest.getSession().getAttribute("user");
        if (empId!=null){
            BaseContext.setId((Long) empId);
        }
        if (userId!=null){
            BaseContext.setId((Long) userId);
        }
        String[] urls={"/front/**","/backend/**","/employee/login","/employee/logout","/common/**","/user/login","/user/getCode"};
        Boolean checkAuth=checkAuth(urls,httpServletRequest.getRequestURI());
        if (checkAuth){
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }
        if (httpServletRequest.getSession().getAttribute("employee")==null&&
                httpServletRequest.getSession().getAttribute("user")==null){
            httpServletResponse.setCharacterEncoding("utf-8");
            httpServletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
            return;
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
        return;
    }


    public Boolean checkAuth(String[] urls,String uri){
        for (String url:urls) {
            if (antPathMatcher.match(url,uri)){
                return true;
            }
        }
        return false;
    }
}
